<template>
  <transition name="sysmtemenus">
    <div class="system-menus" ref="menusRef" :class="{'h5-menus': piniaSystem.getIsH5, 'menus-close': !isOpen}" @click="closeMenuForH5" v-show="h5MenuOpen">
      <transition name="sysmtemenuswrapper">
      <div class="system-menus-wrapper" v-show="h5MenuOpen" @click.stop>
        <div class="menu-switch" v-if="!piniaSystem.getIsH5" @click="toggleMenu">
          <i-line-md-menu-unfold-left v-if="isOpen"/>
          <i-line-md-menu-unfold-right v-else/>
        </div>
        <div class="h5-menu-switch" v-if="piniaSystem.getIsH5" @click="closeMenuForH5">
          <i-ph-caret-double-left-duotone />
        </div>
        <div class="system-menus-content">
          <div class="logo-pc">
            <transition name="openlogo">
              <img :src="channel.logoSmall" v-show="isOpen"/>
            </transition>
            <transition name="closelogo">
              <img :src="channel.logoMini" class="mini-logo" v-show="!isOpen"/>
            </transition>
          </div>
          <div class="search-menus" v-if="piniaSystem.getIsH5">
            <ElInput :prefix-icon="Search" readonly :placeholder="t('home.InputPlaceholder')" @click="openSearchH5" class="zee-form-height-40"/>
            <nav class="search-menus-linker">
              <span @click="gotoLinker('Home')" :class="{active: route.path !== '/SportBTI'}">{{t("home.Casino")}}</span>
              <span @click="gotoLinker('SportBTI')" :class="{active: route.path === '/SportBTI'}">{{t("home.Sport")}}</span>
            </nav>
          </div>
          <div class="system-menus-list linkermenu">
            <dl class="system-menus-item">
              <dt class="system-menus-title">{{ t('home.test17') }}</dt>
              <dd class="system-menus-linker" v-for="menu in menus" :key="menu.linker" :class="{'active': route.name === menu.linker}" @click="goPage(menu)">
                <component :is="menu.icon">ICON</component>
                <transition name="spanname">
                  <span v-if="isOpen">{{ menu.name }}</span>
                </transition>
              </dd>
            </dl>
          </div>
          <div class="system-menus-list linkermenu">
            <dl class="system-menus-item">
              <dt class="system-menus-title">{{ t('home.test18') }}</dt>
              <dd class="system-menus-linker" v-for="peripheral in peripheralFunctions" :key="peripheral.linker" :class="{'active': route.name === peripheral.linker}" @click="goPage(peripheral)">
                <component :is="peripheral.icon">ICON</component>
                <transition name="spanname">
                  <span v-if="isOpen">{{ peripheral.name }}</span>
                </transition>
              </dd>
            </dl>
          </div>
          <div class="system-menus-list settermenu">
            <dl class="system-menus-item">
              <dt class="system-menus-title">{{ t('home.test19') }}</dt>
              <el-popover ref="langpopover" :placement="langplacement" :width="200" trigger="click" @before-enter="lnagSelectorOpened = true" @before-leave="lnagSelectorOpened = false">
                <template #reference>
                  <dd class="system-menus-linker">
                    <img :src="systemLang.resource" alt="" class="lang-logo">
                    <span>{{systemLang.language}}</span>
                    <IIconoirNavArrowDown class="lang-icons" :class="{'lang-icons-opened': lnagSelectorOpened}"/>
                  </dd>
                </template>
                <ul class="system-menus-lang-selector">
                  <li @click="changeLang(item)" v-for="item in langList" :key="item.code">
                    <img :src="item.resource" alt="" class="lang-logo">
                    <span>{{item.language}}</span>
                    <i-mdi-check class="lang-check" v-if="locale === item.locale"/>
                  </li>
                </ul>
              </el-popover>
              <dd class="system-menus-linker" @click="toggleSupport"><i-iconoir-headset-help /><span>{{ t('home.LiveSupport') }}</span></dd>
              <dd class="system-menus-linker"><i-bi-chat-text /><span>{{ t('home.test13') }}</span></dd>
            </dl>
          </div>
          <div class="system-menus-list settermenu themeset">
            <el-popover ref="themepopover" :placement="langplacement" :width="200" trigger="click" @before-enter="themeSelectorOpened = true" @before-leave="themeSelectorOpened = false">
              <template #reference>
                <div class="system-menus-theme" :class="{'menu-theme-close': !isOpen}">
                  <div class="system-menus-theme-icon">
                    <i-line-md-sunny-filled-loop-to-moon-filled-loop-transition v-if="isDark && !piniaSystem.getThemeAuto" class="moon"/>
                    <i-line-md-sunny-filled-loop v-if="!isDark && !piniaSystem.getThemeAuto" class="sun"/>
                    <MaterialSymbolsAutoAwesome v-if="piniaSystem.getThemeAuto" class="auto"/>
                  </div>
                  <div class="system-menus-theme-title">
                    <span v-if="isDark && !piniaSystem.getThemeAuto">{{ t('theme.dark') }}</span>
                    <span v-if="!isDark && !piniaSystem.getThemeAuto">{{ t('theme.light') }}</span>
                    <span v-if="piniaSystem.getThemeAuto">{{ t('theme.auto') }}</span>
                  </div>
                  <IIconoirNavArrowDown class="theme-icons" :class="{'theme-icons-opened': themeSelectorOpened}"/>
                </div>
              </template>
              <ul class="system-menus-theme-selector">
                <li @click="changeTheme(item)" v-for="item in themeList" :key="item.code">
                  <i-line-md-sunny-filled-loop-to-moon-filled-loop-transition v-if="item.value === 'dark'" class="lang-logo moon"/>
                  <i-line-md-sunny-filled-loop  v-if="item.value === 'light'" class="lang-logo sun"/>
                  <MaterialSymbolsAutoAwesome  v-if="item.value === 'auto'" class="lang-logo auto"/>
                  {{ item.label }}
                  <i-mdi-check class="lang-check" v-if="item.active"/>
                </li>
              </ul>
            </el-popover>
          </div>

          <div class="system-menus-list shares" :class="{'close-shares' : !isOpen}">
            <h3>{{ t('home.SocialMedia') }}</h3>
            <ul>
              <li v-for="share in shares" :key="share.id">
                <img v-zlazy:src="share.resource" alt="">
              </li>
            </ul>
          </div>

          <div class="system-menus-list system-time-version" v-show="isOpen">
            <p>{{ t('home.VersionNum') }}: <span>V{{version}}</span></p>
            <p>{{ t('home.GMT') }}</p>
            <p>{{ $t('home.SysTime') }} : <span>{{piniaSystem.getSystemTime}}</span></p>
            <p>{{ $t('home.localTime') }} : <span>{{piniaSystem.getLocalTime}}</span></p>
          </div>
        </div>
      </div>
      </transition>
    </div>
  </transition>

  <Dialog
    v-model:visible="dialogConfig.show"
    v-model:title="dialogConfig.title"
    v-model:autoHeight="dialogConfig.autoHeight"
    :width="dialogConfig.width"
    :headerFixed="dialogConfig.headerFixed"
    :hiddenTitle="dialogConfig.hiddenTitle"
  >
    <HeaderSearchH5 v-model:title="dialogConfig.title" @back="goBack"/>
  </Dialog>
</template>

<script setup lang="ts" name="SystemMenus">
import system from '@/store/system';
import homeApi from '@/api/modules/home';
import gamesApi from '@/api/modules/games';
import { isDark, toggleDark } from '@/utils/dark';
import MaterialSymbolsAutoAwesome from '~icons/material-symbols/auto-awesome'
import systemApi from '@/api/modules/system';
import { parseTime } from '@/utils/format';
import { setInterval } from 'timers/promises';
import { Search } from '@element-plus/icons-vue';

const version = import.meta.env.VITE_APP_VERSION;
const route = useRoute();
const router = useRouter();
const { t, availableLocales, locale } = useI18n();
const piniaSystem = system(); // 系统设置
const channel:any = computed(()=>piniaSystem.getChannel); // 渠道
const systemLang = computed(()=>piniaSystem.getLang);

// 变量
const data: any = reactive({
  isOpen: true,
  h5MenuOpen: piniaSystem.getIsH5 ? false : true,
  menusRef: null,
  menus: [
    {
      icon: shallowRef(defineAsyncComponent(()=>import('~icons/ic/round-home'))),
      name: computed(()=>t('home.text28')),
      linker: 'Home'
    },
    {
      icon: shallowRef(defineAsyncComponent(()=>import('~icons/ion/dice'))),
      name: computed(()=>t('home.Originals')),
      linker: 'OriginalGame'
    },
    {
      icon: shallowRef(defineAsyncComponent(()=>import('~icons/mdi/slot-machine'))),
      name: computed(()=>t('home.Slots')),
      linker: 'SlotGame'
    },
    {
      icon: shallowRef(defineAsyncComponent(()=>import('~icons/ic/outline-live-tv'))),
      name: computed(()=>t('home.LiveCasino')),
      linker: 'LiveGame'
    },
    {
      icon: shallowRef(defineAsyncComponent(()=>import('~icons/cryptocurrency/chips'))),
      name: computed(()=>t('home.title4')),
      linker: 'DeskGame'
    },
  ],
  peripheralFunctions: [
    {
      icon: shallowRef(defineAsyncComponent(()=>import('~icons/ion/ios-people'))),
      name: computed(()=>t('home.Affiliate')),
      linker: 'Affiliate'
    },
    {
      icon: shallowRef(defineAsyncComponent(()=>import('~icons/ic/sharp-stars'))),
      name: computed(()=>t('home.Promotions')),
      linker: 'Promotions'
    },
    {
      icon: shallowRef(defineAsyncComponent(()=>import('~icons/mdi/crown'))),
      name: computed(()=>t('UserInfo.VIPClub')),
      linker: 'Vip'
    },
  ],
  langList: [],
  langplacement: 'top',
  langpopover: null,
  themeList: [
    {
      label: computed(()=>t('theme.dark')),
      value: "dark",
      active: computed(()=>!piniaSystem.getThemeAuto && isDark.value),
    },
    {
      label: computed(()=>t('theme.light')),
      value: "light",
      active: computed(()=>!piniaSystem.getThemeAuto && !isDark.value),
    },
    {
      label: computed(()=>t('theme.auto')),
      value: "auto",
      active: computed(()=>piniaSystem.getThemeAuto),
    }
  ],
  themeSelectorOpened: false,
  shares: [],
  themepopover: null,
  lnagSelectorOpened: false,
  dialogConfig: {
    show: false,
    type: '',
    title: "",
    headerFixed: false,
    width: "100%",
    hiddenTitle: true,
    autoHeight: false
  },
});

const {
  isOpen,
  h5MenuOpen,
  menusRef,
  menus,
  peripheralFunctions,
  langList,
  langplacement,
  langpopover,
  themeList,
  themeSelectorOpened,
  shares,
  themepopover,
  lnagSelectorOpened,
  dialogConfig,
} = toRefs(data);

// 收起或者关闭菜单 pc
const toggleMenu = () => {
  isOpen.value = !isOpen.value;
  isOpen.value ? (langplacement.value = 'top') : (langplacement.value = 'right');
}

const closeMenuForH5 = () => {
  if(piniaSystem.getIsH5){
    h5MenuOpen.value = false;
  }
}

const openMenuForH5 = () => {
  h5MenuOpen.value = true;
  console.log(document.querySelector("#app"))
}

// 修改语言
const changeLang = (lang: any) => {
  piniaSystem.setLang(lang);
  if(availableLocales.indexOf(lang.locale) >= 0){
    locale.value = lang.locale;
  }
  langpopover.value.hide();
}

// 修改暗黑模式
const changeDark = (type:string) => {
  if(isDark.value && type === 'light'){
    toggleDark();
  }else if(!isDark.value && type === 'dark'){
    toggleDark();
  }
  piniaSystem.setDarkTheme(isDark.value);
}

const gotoLinker = (name: string) => {
  router.replace({
    name: name
  });
}

const goBack = () => {
  dialogConfig.value.show = false;
}

// 修改主题
const changeTheme = (theme: any) => {
  if(theme.value === 'dark'){
    piniaSystem.setThemeAuto(false);
    changeDark('dark');
  }else if(theme.value === 'light'){
    piniaSystem.setThemeAuto(false);
    changeDark('light');
  }else if(theme.value === 'auto'){
    piniaSystem.setThemeAuto(true);
    autoTheme();
  }
  themepopover.value.hide();
}

const openSearchH5 = () => {
  dialogConfig.value.show = true;
  dialogConfig.value.title = t('home.search');
  closeMenuForH5();
}

// 自动主题
const autoTheme = () => {
  // 自动主题
  if(window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches){
    changeDark('dark'); // 暗黑
  }else{
    changeDark('light'); // 亮色
  }
}

piniaSystem.getThemeAuto && autoTheme();

// 获取语言配置
const playHallLanguageConfig = () => {
  homeApi.playHallLanguageConfig({channelId: '100000000'}).then((response:any)=>{
    if(response.code === 200){
      langList.value = response.data || [];
      piniaSystem.setLangList(langList.value);
    }
  });
}
playHallLanguageConfig(); // 获取语言配置

// 媒体列表
const getPlatformConfig = () => {
  systemApi.getPlatformConfig({}).then((repsonse:any)=>{
    if(repsonse.code === 200){
      shares.value = repsonse.data.filter((im:any)=> im.dataType == 3);
    }
  })
}
getPlatformConfig();

// 系统时间
const getSysTime = () => {
  systemApi.getSysTime({}).then((response:any)=>{
    if (response.code === 200) {
      piniaSystem.setSystemTime(response.data);
    }
  });
  piniaSystem.setLocalTime();
}
getSysTime();

// 跳转页面
const goPage = (menu: any) => {
  if(menu.linker === 'Affiliate'){
    gamesApi.getExtendChannelInfo({}).then((response:any)=>{
      if(response.code === 200){
        console.log(response.data.extendAddress)
        window.open(`${response.data.extendAddress}?id=${piniaSystem.getLang.code}`, "_blank")
      }
    });
    return false;
  }
  piniaSystem.getIsH5 && closeMenuForH5();
  router.replace({
    name: menu.linker
  });
}

// 隐藏和开启客服支持
const toggleSupport = () => {
  let LiveChatWidget:any = (window as any).LiveChatWidget;
  if (LiveChatWidget) {
    if (LiveChatWidget.get("state").visibility == "hidden") {
      LiveChatWidget.call("hide_greeting");
      LiveChatWidget.call('maximize');
    } else {
      LiveChatWidget.call("hide_greeting");
      LiveChatWidget.call('hide');
    }
  }
}


defineExpose({
  closeMenuForH5,
  openMenuForH5
});
</script>

<style lang="scss" scoped>
@import url('./index.scss');
$timer: 0.4s;
$timer2: 0.7s;
.spanname-enter-active {
  // animation: jackInTheBox $timer;
  animation: fadeInLeft $timer;
}
.spanname-leave-active {
  // animation: bounceOutRight $timer;
  animation: fadeOutLeft $timer;
}
.openlogo-enter-active {
  animation: jackInTheBox $timer;
}
.openlogo-leave-active {
  animation: fadeOut 0;
}
.closelogo-enter-active {
  animation: fadeIn $timer;
}
.closelogo-leave-active {
  animation: fadeOut 0;
}
.sysmtemenus-enter-active {
  animation: fadeIn $timer;
}
.sysmtemenus-leave-active {
  animation: fadeOut $timer;
}
.sysmtemenuswrapper-enter-active {
  animation: fadeInLeft $timer;
}
.sysmtemenuswrapper-leave-active {
  animation: fadeOutLeft $timer;
}
.themebutton-enter-active {
  animation: fadeInLeft $timer;
}
.themebutton-leave-active {
  animation: fadeOut 0;
}
</style>
